package deng.pojo;

import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;

public abstract class SingleScriptGroovyEngine {
	private static final String DEFAULT_SCRIPT_FILE_NAME = System.getProperty("user.home") + "/scripts/myscript.groovy";

	protected Logger logger = Logger.getLogger(getClass());

	protected File scriptFile;	
	protected GroovyScriptEngine groovyEngine;
	protected Binding groovyVariables;
	
	public void setScriptFile(File scriptFile) {
		this.scriptFile = scriptFile;
	}
	public File getScriptFile() {
		return scriptFile;
	}
	public GroovyScriptEngine getGroovyEngine() {
		return groovyEngine;
	}
	public Binding getGroovyVariables() {
		return groovyVariables;
	}
	
	public static String getParentPath(File file) {
		File parent = file.getParentFile();
		if (parent == null) {
			parent = new File(".");
		}
		return parent.getAbsolutePath();
	}
			
	public void initGroovyEngine() {
		try {
			if (scriptFile == null) {
				scriptFile = new File(DEFAULT_SCRIPT_FILE_NAME);				
			}
			groovyVariables = new Binding();
			if (groovyEngine == null) {
				logger.info("Creating GroovyScriptEngine with " + scriptFile);
				groovyEngine = new GroovyScriptEngine(new String[]{getParentPath(scriptFile)});
			} else {
				logger.info("Adding new scriptFile to GroovyScriptEngine: " + scriptFile);
				groovyEngine.getGroovyClassLoader().addClasspath(getParentPath(scriptFile));
			}
			groovyVariables.setVariable("caller", this);
		} catch (IOException e) {
			throw new RuntimeException("Failed to initial Groovy script engine.", e);
		}
	}
	
	public void runGroovyScript() {
    	try {
    		groovyVariables.setVariable("logger", Logger.getLogger(logger.getName() + "_" + scriptFile.getName()));
			logger.debug("Executing groovy script: " + scriptFile);
			groovyEngine.run(scriptFile.getName(), groovyVariables);
		} catch (Exception e) {
			throw new RuntimeException("Failed to execute script " + scriptFile, e);
		}
	}
}
